package com.rollCall.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rollCall.entity.Admin;
import com.rollCall.entity.Jwt;
import com.rollCall.entity.vo.LoginVo;
import com.rollCall.mapper.AdminMapper;
import com.rollCall.mapper.JwtMapper;
import com.rollCall.service.AdminService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.UUID;

import static com.rollCall.common.constant.MessageConstant.*;

/**
 *  
 * @date 2025/2/5
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AdminServiceImpl implements AdminService {
	private final JwtMapper jwtMapper;
	private final AdminMapper adminMapper;
	@Override
	public String login(LoginVo loginVo) {
		QueryWrapper<Admin> eq = new QueryWrapper<Admin>().eq("username", loginVo.getUsername());
		Admin admin = adminMapper.selectOne(eq);
		if (ObjectUtil.isNull(admin)) {
			throw new RuntimeException(ACCOUNT_NOT_FOUND);
		}
		if (!admin.getPassword().equals(loginVo.getPassword())) {
			throw new RuntimeException(PASSWORD_ERROR);
		}
		log.info("登录成功");

		Jwt jwt = jwtMapper.selectOne(new QueryWrapper<Jwt>().eq("admin_id", admin.getId()));
		String uuid = null;
		if (ObjectUtil.isNull(jwt)) {
			jwt = new Jwt();
			jwt.setAdminId(admin.getId());
			uuid = UUID.randomUUID().toString();
			jwt.setJwt(uuid);
			jwtMapper.insert(jwt);
		} else {
			uuid = jwt.getJwt();
		}
		return uuid;
	}

	@Override
	public void register(LoginVo loginVo) {
		String username = loginVo.getUsername();
		QueryWrapper<Admin> queryWrapper = new QueryWrapper<Admin>().eq("username", loginVo.getUsername());
		if (adminMapper.selectCount(queryWrapper) != 0) {
			throw new RuntimeException(USERNAME_EXISTS);
		}
		Admin admin = new Admin();
		admin.setUsername(username);
		admin.setPassword(loginVo.getPassword());
		adminMapper.insert(admin);
	}
}
